package breeze.lepei.der.logo_view.presenter;
import android.graphics.Bitmap;
import breeze.lepei.der.utils.AppTools;
import java.io.IOException;
import breeze.lepei.der.BaseView;
import breeze.lepei.der.logo_view.view.ILogoView;
import breeze.lepei.der.logo_view.view.LogoView;
import breeze.lepei.der.utils.MLog;
import android.content.Context;
import breeze.lepei.der.R;
import breeze.lepei.der.logo_view.model.BackDataModel;
import org.jsoup.nodes.Document;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableEmitter;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import breeze.lepei.der.usersettings.UserSettings;
import android.content.Intent;
import breeze.lepei.der.loginview.view.LoginView;
import android.app.ActivityOptions;
import android.content.pm.PackageInfo;
import android.content.pm.Signature;

public class LogoPresenter implements ILogoPresenter {

	/**
	*@author BREEZE
	*@description 签名验证
	*@param 上下文
	*/
	@Override
	public void checkSignatures(Context context) {
		try{
			PackageInfo info=context.getPackageManager().getPackageInfo(context.getPackageName(),0);
			Signature[] signatures=info.signatures;
			Signature s=signatures[0];
			MLog.log(TAG,"签名：",String.valueOf(s.hashCode()));
		}catch(Exception e){MLog.logE(TAG,e);}
	}
	
	private static String TAG=LogoPresenter.class.getSimpleName();

	/**
	*@author BREEZE
	*@description 获取后台数据
	*@return 后台数据
	*/
	@Override
	public BackDataModel getBackgroundData() {
		try {
			Document doc=Jsoup.connect(mContext.getString(R.string.backdata_link))
				.userAgent(mContext.getString(R.string.phone_ua))
				.get();
			if (doc != null) {
				BackDataModel backdataModel = BackDataModel.getInstance(mContext);
				Element element=doc.getElementById("noteContainer");
				String allData=element.text();
				//TODO：解析数据
				int versionCode=Integer.valueOf(allData.substring(allData.indexOf("版本【") + 3, allData.lastIndexOf("】版本")));
				String announcement=allData.substring(allData.indexOf("公告【") + 3, allData.lastIndexOf("】公告"));
				String downloadLink=allData.substring(allData.indexOf("下载【") + 3, allData.lastIndexOf("】下载"));
				String logoLink=allData.substring(allData.indexOf("图片【") + 3, allData.lastIndexOf("】图片"));
				String isRunning=allData.substring(allData.indexOf("运行【") + 3, allData.lastIndexOf("】运行"));
				String updateInfo=allData.substring(allData.indexOf("更新【") + 3, allData.lastIndexOf("】更新"));
				backdataModel.setVersionCode(versionCode);
				backdataModel.setDownloadLink(downloadLink);
				backdataModel.setAnnouncement(announcement);
				backdataModel.setLogoLink(logoLink);
				backdataModel.putUpdateInfo(updateInfo);
				if ("null".equals(isRunning)) {
					backdataModel.setIsRunning("null");
				} else {
					backdataModel.setIsRunning(isRunning);
				}
				return backdataModel;
			}
			return null;
		} catch (Exception e) {
			MLog.logE(TAG,e);
			return null;
		}
	}

	/**
	*@author BREEZE
	*@description 开始倒计时
	*/
	@Override
	public void startSkipTime() {
		//以线程方式
		BaseView.getExec().execute(new Runnable(){public void run(){
			for(int i=5;i>=0;i--){
				logoview.setSkipTime(i);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					MLog.showBug(mContext,e);
				}
			}
		}});
	}

	/**
	*@author BREEZE
	*@description 设置背景图片
	*/
	@Override
	public void setBackground() {
		BaseView.getExec().execute(new Runnable(){public void run() {
					Observable<BackDataModel> observable=Observable.create(new ObservableOnSubscribe<BackDataModel>(){
							@Override
							public void subscribe(ObservableEmitter<BackDataModel> p1) throws Exception {
								logoview.setInitMessage("获取后台数据......");
								BackDataModel data=getBackgroundData();
								if(data!=null){
									int version=AppTools.getVersionCode(mContext);
									int versionNew=data.getVersionCode();
									MLog.log(TAG,"当前应用版本：",String.valueOf(version));
									MLog.log(TAG,"最新应用版本：",String.valueOf(versionNew));
									if(!"null".equals(data.isRunning())){
										//TODO：停止使用
										logoview.stopUsing(data.isRunning());
										p1.onError(null);
									}
									if(version<versionNew){
										//TODO：检测到更新
										logoview.showNewVersion(data.getVersionCode(),data.getDownloadLink(),data.getUpdateInfo());
										p1.onError(null);
									}else{
										p1.onNext(data);
										p1.onComplete();
									}
								}else{
									MLog.log("===获取后台数据失败===");
								}
							}
						});
					Observer<BackDataModel> server=new Observer<BackDataModel>(){
						@Override
						public void onComplete() {
							logoview.setInitMessage("获取图片......");
							if("null".equals(backdata.getLogoLink())){
								logoview.setBackground(getBingPic());
							}else{
								try {
									logoview.setBackground(AppTools.getWebBitmap(backdata.getLogoLink()));
								} catch (IOException e) {
									logoview.setBackground(getBingPic());
									MLog.logE(TAG,e);
								}
							}
						}

						@Override
						public void onError(Throwable p1) {
						}

						@Override
						public void onNext(BackDataModel p1) {
							backdata=p1;
						}

						@Override
						public void onSubscribe(Disposable p1) {
						}
					};
					observable.subscribe(server);
				}});
	}
	
	private ILogoView logoview;;
	public static BackDataModel backdata;
	private Context mContext;

	/**
	*@author BREEZE
	*@description 获取必应图片
	*@return 数位图
	*/
	@Override
	public Bitmap getBingPic() {
		/*
		 *郭霖bing图片api接口
		 *@data http://guolin.tech/api/bing_pic
		 */
		try {
			String bing_pic_link=AppTools.getWebContent("http://guolin.tech/api/bing_pic");
			MLog.log(bing_pic_link);
			Bitmap bitmap=AppTools.getWebBitmap(bing_pic_link);
			return bitmap;
		} catch (IOException e) {
			MLog.logE(TAG,e);
			return null;
		}
	}
	
	public LogoPresenter(LogoView baseview){
		this.mContext=baseview.getApplicationContext();
		this.logoview=baseview;
	}
}
